package com.fumihiko.modules.job.task;


import com.fumihiko.common.utils.DateTimeUtil;
import com.fumihiko.modules.ca.service.UserAppinfoService;
import com.fumihiko.modules.ca.service.UserTokenService;
import com.fumihiko.modules.ca.vo.UserAppinfoVo;
import com.fumihiko.modules.ca.vo.UserTokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 定时任务2小时自动刷新ACCESSTOKEN
 */
@Component
public class AccessTokenScheduler {

    @Autowired
    private UserAppinfoService userAppinfoService;
    @Autowired
    private UserTokenService userTokenService;


    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    //每隔10S执行一次
    @Scheduled(fixedRate = 1000 * 10)
    public void testTasks() {
        System.out.println("定时任务执行时间：" + dateFormat.format(new Date()));
        List<UserAppinfoVo>  userAppinfoVoList = userAppinfoService.getUserAppinfoList();
        if(null != userAppinfoVoList){
            for(UserAppinfoVo userAppinfoVo : userAppinfoVoList){
                List<UserTokenVo> userTokenVoList = userTokenService.getUserTokenVoObj(userAppinfoVo.getAppId(), userAppinfoVo.getAppSecret());
                for(UserTokenVo userTokenVo: userTokenVoList){
                    if(null != userTokenVo) {
                        Long sec = DateTimeUtil.getTimeMinusToSec(DateTimeUtil.getCurrentTime(), userTokenVo.getExpirationTime());
                        if (sec > 0) {
                            userTokenService.deleteUserTokenVoObj(userAppinfoVo.getAppId(), userAppinfoVo.getAppSecret(), userTokenVo.getAccessToken());
                        }else{
                            continue;
                        }
                    }
                }
//                UserTokenVo userTokenVoDB = new UserTokenVo();
//                userTokenVoDB.setAppId(userAppinfoVo.getAppId());
//                userTokenVoDB.setAppSecret(userAppinfoVo.getAppSecret());
//                String token = TokenProccessor.getInstance().makeToken();
//                userTokenVoDB.setAccessToken(token);
//                userTokenVoDB.setExpirationTime(DateTimeUtil.getChangeDateByHour(DateTimeUtil.getCurrentTime(), SxConstants.HOUR));
//                userTokenService.insertUserTokenObj(userTokenVoDB);
            }
        }

    }

}
